package com.xrit.sunnyday.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.xrit.sunnyday.dao.OrderSettingDao;
import com.xrit.sunnyday.exception.SunnydayException;
import com.xrit.sunnyday.pojo.OrderSetting;
import com.xrit.sunnyday.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Transactional
@Service(interfaceClass = OrderSettingService.class)
public class OrderSettingServiceImpl implements OrderSettingService {
    @Autowired
    private OrderSettingDao orderSettingDao;

    @Override
    public void add(List<OrderSetting> orderSettingList) {
        //遍历每个OrderSetting
        for (OrderSetting orderSetting : orderSettingList) {
            //取出时间
            Date orderDate = orderSetting.getOrderDate();
            //查询是否有当前日期的预约设置
            OrderSetting osInDb = orderSettingDao.findByOrderDate(orderDate);
            if(null!=osInDb){//有当前日期的预约设置
                //判断数据库表中的预约人数是否大于，要更新的可预约人数，大于则抛出异常
                if(osInDb.getReservations()>orderSetting.getNumber()){
                    throw new SunnydayException(orderSetting.getOrderDate()+"中，已预约的人数比你现在设置的可预约人数要大");
                }
                //小于则更新数据库可预约人数
                orderSettingDao.updateNumber(orderSetting);
            }else {
                //没有则添加预约设置
                orderSettingDao.add(orderSetting);
            }
        }
    }

    @Override
    public List<Map<String, Integer>> getDataByMonth(String month) {
        String startDate = month + "-01";
        return orderSettingDao.getDataByMonth(startDate);
    }

    @Override
    public void editNumberByDate(OrderSetting orderSetting) {
        Date orderDate = orderSetting.getOrderDate();
        OrderSetting osInDb = orderSettingDao.findByOrderDate(orderDate);
        if(null!=osInDb){
            if(osInDb.getReservations()>orderSetting.getNumber()){
                throw new SunnydayException(orderSetting.getOrderDate()+"中，已预约的人数比你现在设置的可预约人数要大");
            }
            orderSettingDao.updateNumber(orderSetting);
        }else {
            orderSettingDao.add(orderSetting);
        }
    }
}
